<template>
  <!-- 普通-结果回顾(历史结果) -->
  <div id="wLapplicationItem">
    <div style="height: 100%">
      <splitpanes horizontal>
        <Pane :size="historyPanelTop">
          <Splitpanes class="Splitpanes">
            <Pane size="12">
              <HistoryRqtBtn></HistoryRqtBtn>
            </Pane>
            <Pane size="88">
     <ActiveReportViewer :reportName="rptId" :reportParamter="rptParams" :isShowParamPanel="isSHowParamPanel" />
           </Pane>
          </Splitpanes>
        </Pane>
      </splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, reactive, ref } from 'vue';
import { Pane, Splitpanes } from 'splitpanes';
import { formatDateTime, IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import * as echarts from 'echarts';
import HistoryRqtBtn from './HistoryRqtBtn.vue'
import ImgTxtRpt from './ImgTxtRpt.vue'
import ActiveReportViewer from '@/components/ActiveReportViewer.vue';
import { getOptionValueByCodeGlobalOption, getOptionValueByCodeRptGroupOption } from '@/utils/SysOptionsHelper';

let { proxy }: any = getCurrentInstance();
let historyList = reactive([]); //历史结果数据汇总
let historyResult = reactive([]); //历史结果右侧数据
let historyWls = reactive([]);
let xAxisDatas: any = reactive([]); //chart图 X 坐标
let seriesData = reactive([]);
let loading = ref(false);
let width: any = ref(0.4); //信息列宽度(小数)
let historyPanelTop = ref(100);
let reportList = reactive([]);

/**
 * 宝宝爬变量
*/
const rptId = ref('');
const rptParams: any = reactive({});
const isSHowParamPanel = ref(true);
//暴露接口
defineExpose({
  getResultReview, getWidth, cleanData, getHisResultDot
});

function getWidth(widths: any) {
  width.value = widths;
}

function cleanData() {
  historyList.length = 0;
  historyResult.length = 0;
  seriesData.length = 0;
}

//获取普通的结果回顾
function getHisResultDot(row: any) {
  const jgbjyj = getOptionValueByCodeRptGroupOption('jgbjyj');//结果比较根据
  const jgbjyqlb = getOptionValueByCodeRptGroupOption('jgbjyqlb');//结果比较仪器列表（用,分割）
  const jgbjjg = getOptionValueByCodeRptGroupOption('jgbjjg');//结果比较间隔

  console.log('jgbjyj', jgbjyj);
  // jgbjyj 0姓名  1病历号 2姓名+病历号  3身份证号
  if ((IsEmpty(row.patNa) && jgbjyj == '0')
    || (IsEmpty(row.patNo) && jgbjyj == '1')
    || (IsEmpty(row.patNo) && IsEmpty(row.patNa) && jgbjyj == '2')
    || (IsEmpty(row.idNo) && jgbjyj == '3')
  ) {
    proxy.$emit('getIsDot', false);
    return;
  }

  row.jgbjyj = jgbjyj;
  row.jgbjyqlb = (jgbjyqlb == null || jgbjyqlb == 'null' || jgbjyqlb == undefined ? null : JSON.parse(jgbjyqlb).join(','));
  row.jgbjjg = jgbjjg;
  const url = '/lab/maininfo/findResultRptReviewHistory';
  proxy.$http
    .get(url, { params: row })
    .then((res: any) => {
      if (res.status.code !== 400) {
        if (res.data && res.data === 1) {
          proxy.$emit('getIsDot', true);
        } else {
          proxy.$emit('getIsDot', false);
        }
      }
    })
    .catch((err) => {
      proxy.$emit('getIsDot', false);
    });
}

//获取普通的结果回顾
function getResultReview(row: any) {
  loading.value = true;
  /**隐藏检验结果比较折线图 ycjjjgbjzxt*/
  const a = getOptionValueByCodeGlobalOption('ycjjjgbjzxt');
  if (a && (a === '1' || a === 1)) {
    historyPanelTop.value = 100;
  }

  historyResult.length = 0;
  historyWls.length = 0;
  historyList.length = 0;
  if (historyResult.length <= 0) {
    seriesData.length = 0;
    xAxisDatas.length = 0;
  }
  const jgbjyj = getOptionValueByCodeRptGroupOption('jgbjyj');//结果比较根据
  const jgbjyqlb = getOptionValueByCodeRptGroupOption('jgbjyqlb');//结果比较仪器列表（用,分割）
  const jgbjjg = getOptionValueByCodeRptGroupOption('jgbjjg');//结果比较间隔

  // jgbjyj 0姓名  1病历号 2姓名+病历号  3身份证号
  if ((IsEmpty(row.patNa) && jgbjyj == '0')
    || (IsEmpty(row.patNo) && jgbjyj == '1')
    || (IsEmpty(row.patNo) && IsEmpty(row.patNa) && jgbjyj == '2')
    || (IsEmpty(row.idNo) && jgbjyj == '3')
  ) {
    loading.value = false;
    proxy.$emit('getIsDot', false);
    return;
  }

  row.jgbjyj = jgbjyj;
  row.jgbjyqlb = (jgbjyqlb == null || jgbjyqlb == 'null' || jgbjyqlb == undefined ? null : JSON.parse(jgbjyqlb).join(','));
  row.jgbjjg = jgbjjg;
  const url = '/lab/maininfo/findResultReviewByPatNo';
  proxy.$http
    .get(url, { params: row })
    .then((res: any) => {
      historyList.length = 0;
      if (res.status.code !== 400) {
        historyList.push(...res.data);
        if (historyList.length > 0) {
          proxy.$emit('getIsDot', historyList[0].isDot);
        } else {
          proxy.$emit('getIsDot', false);
        }
        loading.value = false;
      }
      proxy.$nextTick(() => {
        historyListRowClick({ row: historyList[0], rowIndex: 0 });
      });
    })
    .catch((err) => {
      loading.value = false;
      VxeMessage(err, VxeNotifyType.error);
    });
}

/**格式化标头时间 */
function fmtDateTime(val) {
  if (IsEmpty(val)) {
    return '';
  }
  try {
    return formatDateTime(val, 'yyyy-MM-dd');
  } catch (error) {
    return '';
  }
  return '';
}

// 点击历史结果左侧当前行
function historyListRowClick({ row, rowIndex }) {
  if (IsEmpty(row)) {
    return;
  }
  let $Xtable = proxy.$refs.historyResultListTable;
  $Xtable.setCurrentRow(row);
  historyResult.length = 0;
  historyWls.length = 0;
  proxy.$nextTick(() => {
    historyResult.push(...row.result.ansWithResults);
    historyWls.push(...row.result.wls);
    handleHistoryResultData(historyResult, historyWls);
    historyResultRowClick({
      row: historyResult[0],
      rowIndex: 0
    });
  })

}

// 处理后端返回的数据，使数据符合el-table展示格式
function handleHistoryResultData(historyResult, historyWls) {
  loading.value = true;

  const temporaryArr = historyResult;

  // historyResult.length = 0;
  xAxisDatas.length = 0;
  historyWls = historyWls.sort((a, b) => {
    return new Date(b.scheduleDate).valueOf() - new Date(a.scheduleDate).valueOf();
  });

  temporaryArr.forEach((item, idx) => {
    const result = [];
    historyWls.forEach((wl, index) => {
      const resaultData = item.wlResults.find((val) => {
        return wl.id === val.wlId;
      });
      result.push(resaultData);
    });
    item.wlResults = result;
  });
  historyWls.forEach((wl, index) => {
    // X轴
    xAxisDatas.unshift(formatDateTime(wl.scheduleDate, 'yyyy-MM-dd'));
  });
  loading.value = false;
}

// 行点击事件
function historyResultRowClick({ row, rowIndex }) {
  if (IsEmpty(row)) {
    return;
  }
  // this.currentQiRpt = row;
  else {
    (proxy.$refs.historyResultTable as any).setCurrentRow(row);

    initChart(row);
  }
}

// #region 【视图处理】
function initChart(row) {
  proxy.$nextTick(() => {
    seriesData.length = 0;
    let chartDom = document.getElementById('main');
    // chartDom.style.width = '900px';
    // chartDom.style.height = '300px';
    chartDom.style.width =
      (
        document.documentElement.clientWidth -
        document.documentElement.clientWidth * width.value -
        250
      ).toString() + 'px';
    chartDom.style.height =
      (
        document.documentElement.clientHeight -
        document.documentElement.clientHeight * 0.6 -
        100
      ).toString() + 'px';

    let myChart = echarts.init(chartDom);
    // 设置宽度为100%，充满父元素
    let xAxisData = xAxisDatas.reverse();
    let yAxisData = [];
    yAxisData.length = 0;
    if (IsEmpty(row)) {
      return;
    }
    let arrSort = Object.assign([], row.wlResults);
    //arrSort = arrSort.sort((a, b) => { return a.scheduleDate - b.scheduleDate });
    arrSort.forEach((item) => {
      // 取出结果中不为空且不重复的值
      if (!IsEmpty(item.result) && yAxisData.indexOf(item.result) === -1) {
        yAxisData.push(item.result);
      }

      seriesData.push(item.result);
    });
    // 把yAxisData中的数据排序
    yAxisData.sort(setNumberSort);

    const option = {
      legend: {
        type: 'scroll'
      },
      grid: {
        top: '10%',
        bottom: '20px',
        left: '40px',
        right: '40px'
      },
      tooltip: {
        trigger: 'axis',
        confine: true, //是否将 tooltip 框限制在图表的区域内
        backgroundColor: 'rgba(255, 255, 255, 0.8)',
        borderRadius: 5,
        extraCssText: 'box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);',
        padding: [5, 10],
        textStyle: {
          color: '#333'
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        // splitLine: {
        //   show: true
        // },
        data: xAxisData
      },
      yAxis: {
        type: 'value'
      },
      series: {
        type: 'line',
        data: seriesData,
        symbolSize: 6,
        lineStyle: {
          color: '#409eff'
        },
        itemStyle: {
          color: '#f56c6c'
        },
        connectNulls: true //断点链接
      }
    };
    myChart.clear();
    myChart.setOption(option, true); //第二个参数 true 用来清除上次数据
  });
}

//为图表计算高度
function chartssize(container, charts) {
  function getStyle(el, name) {
    if (window.getComputedStyle) {
      return window.getComputedStyle(el, null);
    } else {
      return el.currentStyle;
    }
  }
  const w = getStyle(container, 'width').width;
  const h = getStyle(container, 'height').height;
  charts.style.height = h;
}

// 按数值排序
function setNumberSort(x, y) {
  if (x < y) {
    return -1;
  } else if (x > y) {
    return 1;
  } else {
    return 0;
  }
}

/**
 * 单元格背景颜色
 *【1】是否启用系统选项颜色配置  encolorsetting
 *【2】偏高结果颜色  hresultcolor
 *【3】偏低结果颜色  lresultcolor
 *【4】阳性结果颜色  presultcolor
 *【5】正常结果颜色  mresultcolor
 *【6】弱阳性结果颜包  qresultcolor
 *【7】错误结果颜色  errresultcolor
 *【8】阴性结果颜色  nresultcolor
 *【9】结果标志颜色显示方式 jgbzysxsfs (0:背景色  1:文字颜色)
 */
function calcCellBgColorNew(row, rowIndex, index) {
  //偏高【结果】
  if (row && row.wlResults && row.wlResults[index] && row.wlResults[index].resultFlag === 'H') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('hresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#ff0000', color: '#fff' };
  }
  //偏低【结果】
  if (row && row.wlResults && row.wlResults[index] && row.wlResults[index].resultFlag === 'L') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('lresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#0035ff', color: '#fff' };
  }
  /**阳性【结果】 */
  if (row && row.wlResults && row.wlResults[index] && row.wlResults[index].resultFlag === 'P') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('presultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#0035ff', color: '#fff' };
  }
  /**弱阳性【结果】 */
  if (row && row.wlResults && row.wlResults[index] && row.wlResults[index].resultFlag === 'Q') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('qresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#0035ee', color: '#fff' };
  }
  /**错误【结果】 */
  if (row && row.wlResults && row.wlResults[index] && row.wlResults[index].resultFlag === 'E') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('errresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { background: '#800000', color: '#fff' };
  }
  /**正常【结果】 */
  if (row && row.wlResults && row.wlResults[index] && row.wlResults[index].resultFlag === 'M') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('mresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { color: '#000' };
  }
  /**阴性【结果】 */
  if (row && row.wlResults && row.wlResults[index] && row.wlResults[index].resultFlag === 'N') {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      const c = getOptionValueByCodeGlobalOption('nresultcolor');
      if (!IsEmpty(c)) {
        return { background: c, color: '#fff' };
      }
    }
    return { color: '#000' };
  }
}

// 浏览
function previewRpt() {
  const rowList = wLTable.value?.getCheckboxRecords(true);
  if (rowList.length === 0) {
    if (currentWork || IsEmpty(currentWork.id)) {
      VxeMessage('请选择一条数据', VxeNotifyType.warning);
      return;
    }
  }
  isPreviewRpt.value = false;
  tableLoading.value = true;
  reportList.length = 0;
  if (IsEmpty(rowList)) {
    tableLoading.value = false;
    VxeMessage('预览失败', VxeNotifyType.error);
  }
  proxy.$http
    .post('/lab/maininfo/viewRptBatch', rowList)
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        Object.assign(reportList, res.data);
        isPreviewRpt.value = true;
        tableLoading.value = false;
      }
    })
    .catch((err: any) => {
      tableLoading.value = false;
      VxeMessage('预览失败', VxeNotifyType.error);
    });
}
</script>

<style lang="scss" scoped>
#wLapplicationItem {
  height: 100%;
}

#main {
  width: 100%;
  height: 100%;
}

.chartBox {
  height: 100%;
  width: 100%;
}
</style>
